﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SharpSoft.WPF.Controls
{
    /// <summary>
    /// Pagination.xaml 的交互逻辑
    /// </summary>
    public partial class Pagination : TextBlock
    {
        public Pagination()
        {
            InitializeComponent();
        }


        public int PageCount
        {
            get { return (int)GetValue(PageCountProperty); }
            set { SetValue(PageCountProperty, value); }
        }

        public static readonly DependencyProperty PageCountProperty =
            DependencyProperty.Register("PageCount", typeof(int), typeof(Pagination), new PropertyMetadata(0, (d, e) => { ((Pagination)d).Refresh(); }));




        public int CurrentPage
        {
            get { return (int)GetValue(CurrentPageProperty); }
            set { SetValue(CurrentPageProperty, value); }
        }

        public static readonly DependencyProperty CurrentPageProperty =
            DependencyProperty.Register("CurrentPage", typeof(int), typeof(Pagination), new PropertyMetadata(0, (d, e) => { ((Pagination)d).Refresh(); }));



        public void Refresh()
        {
            this.Inlines.Clear();
            if (PageCount == 0)
            {
                return;
            }
            Hyperlink hypre = new Hyperlink(new Run("上一页 ") { }) { Tag = CurrentPage - 1 };
            this.Inlines.Add(hypre);
            if (CurrentPage > 0)
            {
                hypre.Click += Hy_Click;
            }
            else
            {
                hypre.Foreground = Brushes.Gray;
            }
            for (int i = 0; i < PageCount; i++)
            {
                if (i == CurrentPage)
                {
                    this.Inlines.Add(new Run((i + 1).ToString() + " "));
                }
                else
                {
                    Hyperlink hy = new Hyperlink(new Run((i + 1).ToString() + " ")) { Tag = i };
                    hy.Click += Hy_Click;
                    this.Inlines.Add(hy);
                }

            }
            Hyperlink hynext = new Hyperlink(new Run("下一页")) { Tag = CurrentPage + 1 };
            this.Inlines.Add(hynext);
            if (CurrentPage < PageCount - 1)
            {
                hynext.Click += Hy_Click;
            }
            else
            {
                hynext.Foreground = Brushes.Gray;
            }
        }
        public event Action<int> GotoPage;
        private void Hy_Click(object sender, RoutedEventArgs e)
        {
            Hyperlink hy = (Hyperlink)sender;
            int index = (int)hy.Tag;
            GotoPage?.Invoke(index);
        }
    }
}
